import 'dart:async';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/foundation.dart';
import 'audio_exception.dart';

/// 音频播放工具类
/// 封装 audioplayers 包功能，提供统一的音频播放接口
class AudioPlayerTool {
  // 单例模式
  static final AudioPlayerTool _instance = AudioPlayerTool._internal();
  factory AudioPlayerTool() => _instance;
  AudioPlayerTool._internal();

  // 音频播放器实例
  static final AudioPlayer _player = AudioPlayer();

  // 流控制器
  static final StreamController<String> _errorController =
      StreamController<String>.broadcast();

  /// 初始化音频播放器
  static Future<void> initialize() async {
    try {
      // 设置音频播放模式
      await _player.setReleaseMode(ReleaseMode.stop);

      // 监听播放器状态变化来捕获错误
      _player.onPlayerStateChanged.listen((state) {
        if (state == PlayerState.stopped) {
          // 可以在这里处理播放停止的情况
          if (kDebugMode) {
            debugPrint('播放器状态: $state');
          }
        }
      });

      if (kDebugMode) {
        debugPrint('AudioPlayerTool 初始化成功');
      }
    } catch (error) {
      if (kDebugMode) {
        debugPrint('AudioPlayerTool 初始化失败: $error');
      }
      _errorController.add('音频播放器初始化失败: $error');
    }
  }

  /// 播放位置流
  static Stream<Duration> get positionStream => _player.onPositionChanged;

  /// 播放时长流
  static Stream<Duration> get durationStream => _player.onDurationChanged;

  /// 播放状态流
  static Stream<PlayerState> get stateStream => _player.onPlayerStateChanged;

  /// 播放完成流
  static Stream<void> get completionStream => _player.onPlayerComplete;

  /// 错误流
  static Stream<String> get errorStream => _errorController.stream;

  /// 当前播放状态
  static PlayerState get state => _player.state;

  /// 当前播放位置
  static Future<Duration> get position async {
    final pos = await _player.getCurrentPosition();
    return pos ?? Duration.zero;
  }

  /// 当前播放时长
  static Future<Duration> get duration async {
    final dur = await _player.getDuration();
    return dur ?? Duration.zero;
  }

  /// 是否正在播放
  static bool get isPlaying => _player.state == PlayerState.playing;

  /// 是否已暂停
  static bool get isPaused => _player.state == PlayerState.paused;

  /// 是否已停止
  static bool get isStopped => _player.state == PlayerState.stopped;

  /// 播放音频
  /// [url] 音频文件 URL
  /// [position] 可选的起始播放位置
  static Future<void> play(String url, {Duration? position}) async {
    try {
      if (kDebugMode) {
        debugPrint('开始播放音频: $url');
      }

      // 如果 URL 为空，抛出异常
      if (url.isEmpty) {
        throw const AudioPlayException('音频 URL 不能为空', code: 'EMPTY_URL');
      }

      // 检查 URL 格式
      if (!_isValidUrl(url)) {
        throw AudioPlayException('无效的音频 URL: $url', code: 'INVALID_URL');
      }

      // 播放音频
      await _player.play(UrlSource(url), position: position);

      if (kDebugMode) {
        debugPrint('音频播放成功');
      }
    } on AudioException {
      rethrow;
    } catch (error) {
      if (kDebugMode) {
        debugPrint('播放音频失败: $error');
      }
      final audioError =
          AudioPlayException('播放失败: $error', originalError: error);
      _errorController.add(audioError.message);
      throw audioError;
    }
  }

  /// 暂停播放
  static Future<void> pause() async {
    try {
      await _player.pause();
      if (kDebugMode) {
        debugPrint('音频已暂停');
      }
    } catch (error) {
      if (kDebugMode) {
        debugPrint('暂停播放失败: $error');
      }
      _errorController.add('暂停失败: $error');
      rethrow;
    }
  }

  /// 继续播放
  static Future<void> resume() async {
    try {
      await _player.resume();
      if (kDebugMode) {
        debugPrint('音频继续播放');
      }
    } catch (error) {
      if (kDebugMode) {
        debugPrint('继续播放失败: $error');
      }
      _errorController.add('继续播放失败: $error');
      rethrow;
    }
  }

  /// 停止播放
  static Future<void> stop() async {
    try {
      await _player.stop();
      if (kDebugMode) {
        debugPrint('音频已停止');
      }
    } catch (error) {
      if (kDebugMode) {
        debugPrint('停止播放失败: $error');
      }
      _errorController.add('停止失败: $error');
      rethrow;
    }
  }

  /// 跳转到指定位置
  /// [position] 目标播放位置
  static Future<void> seekTo(Duration position) async {
    try {
      await _player.seek(position);
      if (kDebugMode) {
        debugPrint('跳转到位置: ${position.inSeconds}秒');
      }
    } catch (error) {
      if (kDebugMode) {
        debugPrint('跳转失败: $error');
      }
      _errorController.add('跳转失败: $error');
      rethrow;
    }
  }

  /// 设置音量
  /// [volume] 音量值 (0.0 - 1.0)
  static Future<void> setVolume(double volume) async {
    try {
      // 确保音量值在有效范围内
      final clampedVolume = volume.clamp(0.0, 1.0);
      await _player.setVolume(clampedVolume);
      if (kDebugMode) {
        debugPrint('音量设置为: $clampedVolume');
      }
    } catch (error) {
      if (kDebugMode) {
        debugPrint('设置音量失败: $error');
      }
      _errorController.add('设置音量失败: $error');
      rethrow;
    }
  }

  /// 获取当前音量
  /// 注意：audioplayers 包可能不支持获取音量，返回默认值
  static Future<double> getVolume() async {
    try {
      // audioplayers 包目前可能不支持获取音量
      // 这里返回默认音量值
      return 1.0;
    } catch (error) {
      if (kDebugMode) {
        debugPrint('获取音量失败: $error');
      }
      return 1.0; // 默认音量
    }
  }

  /// 设置播放速度
  /// [rate] 播放速度 (0.5 - 2.0)
  static Future<void> setPlaybackRate(double rate) async {
    try {
      // 确保播放速度在有效范围内
      final clampedRate = rate.clamp(0.5, 2.0);
      await _player.setPlaybackRate(clampedRate);
      if (kDebugMode) {
        debugPrint('播放速度设置为: $clampedRate');
      }
    } catch (error) {
      if (kDebugMode) {
        debugPrint('设置播放速度失败: $error');
      }
      _errorController.add('设置播放速度失败: $error');
      rethrow;
    }
  }

  /// 释放资源
  static Future<void> dispose() async {
    try {
      await _player.dispose();
      await _errorController.close();
      if (kDebugMode) {
        debugPrint('AudioPlayerTool 资源已释放');
      }
    } catch (error) {
      if (kDebugMode) {
        debugPrint('释放资源失败: $error');
      }
    }
  }

  /// 获取播放器实例（用于高级操作）
  static AudioPlayer get player => _player;

  /// 验证 URL 是否有效
  static bool _isValidUrl(String url) {
    try {
      final uri = Uri.parse(url);
      return uri.hasScheme && (uri.scheme == 'http' || uri.scheme == 'https');
    } catch (e) {
      return false;
    }
  }

  /// 格式化时长为可读字符串
  static String formatDuration(Duration duration) {
    final minutes = duration.inMinutes;
    final seconds = duration.inSeconds % 60;
    return '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  }

  /// 检查音频播放器是否可用
  static bool get isAvailable {
    try {
      return _player.state != PlayerState.disposed;
    } catch (e) {
      return false;
    }
  }

  /// 预加载音频（不播放）
  static Future<void> preload(String url) async {
    try {
      if (url.isEmpty) {
        throw const AudioLoadException('预加载 URL 不能为空', code: 'EMPTY_URL');
      }

      if (!_isValidUrl(url)) {
        throw AudioLoadException('无效的预加载 URL: $url', code: 'INVALID_URL');
      }

      // 使用 setSource 预加载音频
      await _player.setSource(UrlSource(url));

      if (kDebugMode) {
        debugPrint('音频预加载成功: $url');
      }
    } on AudioException {
      rethrow;
    } catch (error) {
      if (kDebugMode) {
        debugPrint('预加载音频失败: $error');
      }
      final audioError =
          AudioLoadException('预加载失败: $error', originalError: error);
      _errorController.add(audioError.message);
      throw audioError;
    }
  }
}
